<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图 -->
    <el-card>
      <!-- 添加角色列表区域 -->
      <el-row>
        <el-col><el-button type="primary">添加角色</el-button></el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <!-- 通过:data=roleList来绑定数据源 -->
       <el-table
        border
        stripe
        :data="roleList"
        style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1 ===0 ?'bdtop' :'' ,'vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限 -->
              <el-col :span="19">
                <!-- 通过for循环嵌套渲染二级权限 -->
                <el-row :class="[i2 ===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <!-- 左边二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}
                   </el-tag>
                   <i class="el-icon-caret-right"></i>
                   </el-col>
                  <!-- 右边三级权限 -->
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children"
                    :key="item3.id"
                    @close="removeRightById(scope.row,item3.id)"
                    closable type="warning">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column
          type="index">
        </el-table-column>
        <el-table-column
          prop="roleName"
          label="角色名称"
          >
        </el-table-column>
         <el-table-column
          prop="roleDesc"
          label="角色描述"
          >
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button type="warning" icon="el-icon-setting"  @click='showSetRightDialog(scope.row)' size="mini">分配权限</el-button>
          </template>
        </el-table-column>
       </el-table>
    </el-card>
    <!-- 展开分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      @close="setRightDialogClosed"
      width="50%">
      <!-- 树形控件 -->
      <el-tree ref="treeRef"  show-checkbox :data="rightsList"
       node-key="id" default-expand-all
       :default-checked-keys="defKeys"
        :props="treeProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data(){
    return{
      // 所有角色的列表数据
      roleList:[],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible:false,
      // 所有权限的数据
      rightsList:[],
      // 树形控件的属性绑定对象
      treeProps:{
        label:"authName",
        children:'children'
      },
      // 默认选中的节点id的数值
      defKeys:[],
      // 当前即将分配权限的id
      roleId:''
    }
  },
  created(){
    this.getRoleList()
  },
  methods:{
    // 获取所有的角色列表
    getRoleList(){
      this.axios.get('roles').then(res=>{
        console.log(res)
        if(res.data.meta.status !== 200){
          return this.$message.error("获取角色列表失败")
        }
        this.roleList=res.data.data
      })
    },
    // 根据id删除对用的权限(角色的id,对应要删除的权限的id)
    removeRightById(role,rightId){
      // 弹框提示是否要删除
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.axios.delete(`roles/${role.id}/rights/${rightId}`).then(res=>{
            console.log(res)
            if(res.data.meta.status !== 200){
              return this.$message.error("删除权限失败")
            }else{
              role.children = res.data.data
            }
          })
          this.$message.success('删除成功!')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    // 展示分配权下对话框
    showSetRightDialog(role){
      this.roleId=role.id
      // 获取所有权限的数据
      this.axios.get('rights/tree').then(res=>{
        console.log(res)
        if(res.data.meta .status !== 200){
          return this.$message.error("获取权限数据失败")
        }
        this.rightsList=res.data.data
        console.log(this.rightsList)
      })
      // 递归获取三级权限节点id
      this.getLeafKeys(role,this.defKeys)
      this.setRightDialogVisible=true
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed(){
      this.defKeys=[]
    },
    // 点击为角色分配权限
    allotRights(){
      const keys=[
        // 获取所有已选中的id数组
        ...this.$refs.treeRef.getCheckedKeys(),
        // 获取所有
        ...this.$refs.treeRef.getHalfCheckedNodes()
      ]
      const idStr=keys.join(",")
      console.log(keys)
      this.axios.post(`roles/${this.roleId}/rights`,{rids:idStr}).then(res=>{
        console.log(res)
        if(res.data.meta.status !== 200){
          return this.$message.error("分配权限失败")
        }
        this.$message.success("分配权限成功")
        this.getRoleList()
        // 隐藏对话框
        this.setRightDialogVisible=false
      })
    },
    // 定义一个递归函数,通过递归函数获角色下所有三级权限的id,并保存到defKys数组中
    getLeafKeys(node,arr){
      // 如果当前node节点不包含children属性,则是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item=>{
        this.getLeafKeys(item,arr)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display:flex;
  align-items:center;
}
</style>
